<!--
 工位-工装绑定页面
 -->

<template>
  <div class="tool-station-set">
    <!-- 工位示意 -->
    <el-card shadow="never">
      <div class="grid grid-cols-3" style="place-items: center">
        <div
          v-for="(s, index) in stationList"
          :key="index"
          :style="{
            width: '50px',
            height: '50px',
            cursor: 'pointer',
            borderRadius: '25px',
            display: 'flex',
            margin: '20px',
            justifyContent: 'center',
            alignItems: 'center',
            border: s.toolCode ? '0' : '2px solid var(--el-border-color)',
            boxShadow: s.stationNum === selectedStationNum ? 'var(--el-box-shadow-dark)' : '',
            background: s.toolCode ? 'var(--el-color-success-light-3)' : '',
          }"
          @click="handleStationClick(s.stationNum)"
        >
          {{ s.stationNum }}
        </div>
      </div>
    </el-card>

    <!-- 工装码列表 -->
    <div>
      <el-table :data="toolCodeList" @row-click="handleRowClick">
        <el-table-column type="index" width="60px" label="序号"></el-table-column>
        <el-table-column prop="toolCode" :sortable="true" label="工装码"></el-table-column>
        <el-table-column prop="stationNum" :sortable="true" label="工位">
          <template #default="{ row }">
            {{ row.stationNum ?? "未绑定" }}
          </template>
        </el-table-column>
        <el-table-column>
          <template #header>
            <el-button type="primary" icon="Plus" round @click="handleToolAdd">新增</el-button>
          </template>
          <template #default="{ row }">
            <el-popconfirm
              title="确认删除当前工装？"
              confirm-button-text="是"
              cancel-button-text="否"
              placement="right"
              @confirm="handleToolDelete(row.toolCode)"
            >
              <template #reference>
                <el-button type="danger" icon="delete" link size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import deviceApi from "@/api/business/device.api";
import { useSensorStore } from "@/store/business/sensor.store";
const sensorStore = useSensorStore();

onMounted(async () => {
  await fetchStationCount();
  refreshStationList();
});

// 托盘码列表（托盘码-对应的工位号）
const toolCodeList = sensorStore.allTools;
const stationList = ref<{ stationNum: number; toolCode: string }[]>([]);

/**
 * 刷新工位按钮状态
 */
function refreshStationList() {
  stationList.value.forEach((item) => {
    item.toolCode =
      toolCodeList.find((tool) => tool.stationNum === item.stationNum)?.toolCode ?? "";
  });
}

// 当前选中的工位
const selectedStationNum = ref<number>(null);

/**
 * 获取工位数并生成空的工位按钮数据
 */
const fetchStationCount = async () => {
  try {
    const count = await deviceApi.getRealStationCount();
    for (let i = 1; i <= count; i++) {
      stationList.value.push({
        stationNum: i,
        toolCode: "",
      });
    }
  } catch (error) {
    ElMessage.error("获取工位数量失败。" + error);
  }
};

/**
 * 工位按钮点击事件
 * @param stationNum
 */
function handleStationClick(stationNum: number) {
  selectedStationNum.value = stationNum;
}

/**
 * 行点击事件
 * @param row
 */
function handleRowClick(row: { toolCode: string; stationNum: number }) {
  if (!selectedStationNum.value) return;

  sensorStore.bindToolAndStation(row.toolCode, selectedStationNum.value);
  refreshStationList();

  selectedStationNum.value = null;
}

/**
 * 工装添加按钮点击事件
 */
function handleToolAdd() {
  ElMessageBox.prompt("请输入工装码", "添加工装", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[A-Za-z0-9_-]+$/,
    inputErrorMessage: "非法字符",
  }).then(({ value }) => {
    sensorStore.addTool(value);
  });
}
/**
 * 工装删除按钮点击事件
 */
function handleToolDelete(toolCode: string) {
  sensorStore.delTool(toolCode);
  refreshStationList();
}
</script>

<style scoped lang="scss"></style>
